const jsonwebtoken = require("jsonwebtoken");
config = require("../config/config.json");

const createToken = (payload) =>
  jsonwebtoken.sign(payload, config.jwt.secret, { expiresIn: config.jwt.Time });

const createToken_refresh = (payload) =>
  jsonwebtoken.sign(payload, config.jwt.secret, {
    expiresIn: config.jwt.refreshTime,
  });
//定义一个中间件函数，用于jwt身份认证,识别token中的username等用户信息，用于接口中使用

const verifyToken = (req, res, next) => {
  if (req.headers["authorization"]) {
    const token = req.headers["authorization"].replace("Bearer ", "");
    if (!token) {
      const err_body = {
        status: 401,
        messgae: "NO Token provided",
      };
      return res.send(err_body);
    }

    jsonwebtoken.verify(token, config.jwt.secret, (err, decoded) => {
      if (err) {
        const err_body = {
          status: 401,
          message: "Failed to Authenticate Token",
        };
        return res.send(err_body);
      } else {
        req.params = {
          ...req.query,
          ...req.body,
          username: decoded.PhoneNumber,
        };
        next();
      }
    });
  } else {
    const err_body = {
      status: 401,
      messgae: "NO Token provided",
    };
    return res.send(err_body);
  }
};

const getUserId = (req, res, next) => {
  if (req.headers["authorization"]) {
    const token = req.headers["authorization"].replace("Bearer ", "");
    if (!token) {
    }
    jsonwebtoken.verify(token, config.jwt.secret, (err, decoded) => {
      if (err) {
      } else {
        req.params = {
          ...req.query,
          ...req.body,
          username: Number(decoded.PhoneNumber),
        };
      }
    });
  } else {
  }
  next();
};

module.exports = { createToken, createToken_refresh, verifyToken, getUserId };
